﻿#include "biz.h"
#include "ui_biz.h"

Biz::Biz(QWidget *parent) :
    BizEditor(parent),
    ui(new Ui::Biz)
{
    ui->setupUi(this);

    loadDetailColWidthFlag=false;
    loadStuffColWidthFlag=false;
    table=TD_EPIBOLY_INDEX;
    detailTable=TD_EPIBOLY_DETAIL;
    stuffTable=TD_EPIBOLY_STUFF;

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->indexView->setModel(model);

    detailModel=new QSqlTableModel(this);
    detailModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->detailView->setModel(detailModel);

    stuffModel=new QSqlTableModel(this);
    stuffModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->stuffView->setModel(stuffModel);

    ui->indexView->setEditTriggers(QTableView::NoEditTriggers);
    ui->detailView->setEditTriggers(QTableView::NoEditTriggers);
    ui->stuffView->setEditTriggers(QTableView::NoEditTriggers);

    if(loadColumnWidth())
    {
        loadColumnWidthFlag=true;
        loadDetailColWidthFlag=true;
        loadStuffColWidthFlag=true;
    }

    updateView();
    createMenu();
}

Biz::~Biz()
{
    delete ui;
}

void Biz::updateView()
{
    updateViewUnfinish();
}

void Biz::createMenu()
{
    menu=new QMenu(this);
    generateMenu();
}

void Biz::generateMenu()
{
    if(part != "sd")
    {
        menu->addAction(QStringLiteral("添加..."),this,&Biz::newItem);
        menu->addSeparator();
    }
    menu->addAction(QStringLiteral("未完成记录"),this,&Biz::updateView);
    menu->addAction(QStringLiteral("所有记录"),this,&Biz::updateViewAll);
    menu->addSeparator();
    menu->addAction(QStringLiteral("查找..."),this,&Biz::search);

    if(part != "sd")
    {
        menu->addSeparator();
        menu->addAction(QStringLiteral("【入库】"),this,&Biz::en_stock);
        menu->addAction(QStringLiteral("【报损】"),this,&Biz::en_loss);
        menu->addAction(QStringLiteral("【计划完成】"),this,&Biz::en_finish_direct);
        menu->addSeparator();
        menu->addAction(QStringLiteral("进入编辑模式"),this,&Biz::edit_on);
    }
}

void Biz::en_remove()
{
    QModelIndex index=ui->detailView->currentIndex();
    if(index.isValid())
    {
        QModelIndex mIndex=index.sibling(index.row(),5);
        if(detailModel->data(mIndex).toString() != ST_WAIT)
        {
            QMessageBox::warning(this,QStringLiteral("状态无效"),QStringLiteral("只有【等待处理】才可以删除！"));
            return;
        }
        detailModel->removeRow(index.row());
    }
}

bool Biz::loadColumnWidth()
{
    if(!QFile::exists(userLand + ETC_BIZ))
        return false;
    else
    {
        QSettings set(userLand + ETC_BIZ,QSettings::IniFormat);
        int width=set.value("Biz/width").toInt();
        int height=set.value("Biz/height").toInt();
        if(width >= 720 && height >= 480)
            this->resize(width,height);

        colWidth.insert(3,set.value("BizColumnWidth/date").toInt());
        colWidth.insert(4,set.value("BizColumnWidth/contractor").toInt());
        colWidth.insert(5,set.value("BizColumnWidth/name").toInt());
        colWidth.insert(6,set.value("BizColumnWidth/number").toInt());
        colWidth.insert(7,set.value("BizColumnWidth/request").toInt());
        colWidth.insert(8,set.value("BizColumnWidth/status").toInt());

        detailColWidth.insert(2,set.value("DetailColWidth/date").toInt());
        detailColWidth.insert(3,set.value("DetailColWidth/name").toInt());
        detailColWidth.insert(4,set.value("DetailColWidth/number").toInt());
        detailColWidth.insert(5,set.value("DetailColWidth/status").toInt());
        loadDetailColWidthFlag=true;

        stuffColWidth.insert(2,set.value("StuffColWidth/name").toInt());
        stuffColWidth.insert(3,set.value("StuffColWidth/number").toInt());
        stuffColWidth.insert(4,set.value("StuffColWidth/status").toInt());
        loadStuffColWidthFlag=true;

        return true;
    }
}

void Biz::saveColumnWidth()
{
    QSettings set(userLand + ETC_BIZ,QSettings::IniFormat);
    set.setValue("Biz/width",this->width());
    set.setValue("Biz/height",this->height());

    set.setValue("BizColumnWidth/date",ui->indexView->columnWidth(3));
    set.setValue("BizColumnWidth/contractor",ui->indexView->columnWidth(4));
    set.setValue("BizColumnWidth/name",ui->indexView->columnWidth(5));
    set.setValue("BizColumnWidth/number",ui->indexView->columnWidth(6));
    set.setValue("BizColumnWidth/request",ui->indexView->columnWidth(7));
    set.setValue("BizColumnWidth/status",ui->indexView->columnWidth(8));

    set.setValue("DetailColWidth/date",ui->detailView->columnWidth(2));
    set.setValue("DetailColWidth/name",ui->detailView->columnWidth(3));
    set.setValue("DetailColWidth/number",ui->detailView->columnWidth(4));
    set.setValue("DetailColWidth/status",ui->detailView->columnWidth(5));

    set.setValue("StuffColWidth/name",ui->stuffView->columnWidth(2));
    set.setValue("StuffColWidth/number",ui->stuffView->columnWidth(3));
    set.setValue("StuffColWidth/status",ui->stuffView->columnWidth(4));
}

void Biz::setHeaderData()
{
    ui->indexView->hideColumn(0);   //id
    ui->indexView->hideColumn(1);   //uid
    ui->indexView->hideColumn(2);   //plan_id
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("日期"));    //date
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("承包商"));   //contractor
    model->setHeaderData(5,Qt::Horizontal,QStringLiteral("名称"));    //name
    model->setHeaderData(6,Qt::Horizontal,QStringLiteral("数量"));    //number
    model->setHeaderData(7,Qt::Horizontal,QStringLiteral("要求"));    //request
    model->setHeaderData(8,Qt::Horizontal,QStringLiteral("状态"));    //status
    model->setHeaderData(9,Qt::Horizontal,QStringLiteral("备注"));

    if(loadColumnWidthFlag)
    {
        QMap<int,int>::const_iterator itor;
        for(itor = colWidth.constBegin(); itor != colWidth.constEnd(); itor++ )
        {
            int width=itor.value();
            if(width <= 0)
                width=100;
            else if(width >= this->width())
                width =200;

            ui->indexView->setColumnWidth(itor.key(),width);
        }
    }
}

void Biz::newItem()
{
    BizAdd bizAdd;
    bizAdd.move(this->x() + 50,this->y() + 50);
    bizAdd.exec();
    updateView();
}

void Biz::edit_on()
{
    isEdit=true;
    ui->indexView->setEditTriggers(QTableView::DoubleClicked);
    ui->detailView->setEditTriggers(QTableView::DoubleClicked);
    ui->stuffView->setEditTriggers(QTableView::DoubleClicked);
    updateMenu();
}

void Biz::edit_off()
{
    isEdit=false;
    ui->indexView->setEditTriggers(QTableView::NoEditTriggers);
    ui->detailView->setEditTriggers(QTableView::NoEditTriggers);
    ui->stuffView->setEditTriggers(QTableView::NoEditTriggers);
    updateMenu();
}

void Biz::revert()
{
    if(ui->indexView->currentIndex().isValid())
        model->revertAll();

    if(ui->detailView->currentIndex().isValid())
        detailModel->revertAll();

    if(ui->stuffView->currentIndex().isValid())
        stuffModel->revertAll();
}

void Biz::save()
{
    if(ui->indexView->currentIndex().isValid())
        model->submitAll();

    if(ui->detailView->currentIndex().isValid())
        detailModel->submitAll();

    if(ui->stuffView->currentIndex().isValid())
        stuffModel->submitAll();
}

void Biz::updateDetail(const QString &uid)
{
    detailModel->setTable(detailTable);
    detailModel->setFilter(QString("uid = '%1'").arg(uid));
    detailModel->select();

    ui->detailView->hideColumn(0);
    ui->detailView->hideColumn(1);
    detailModel->setHeaderData(2,Qt::Horizontal,QStringLiteral("日期"));
    detailModel->setHeaderData(3,Qt::Horizontal,QStringLiteral("名称"));
    detailModel->setHeaderData(4,Qt::Horizontal,QStringLiteral("数量"));
    detailModel->setHeaderData(5,Qt::Horizontal,QStringLiteral("状态"));
    detailModel->setHeaderData(6,Qt::Horizontal,QStringLiteral("备注"));

    if(loadDetailColWidthFlag)
    {
        QMap<int,int>::const_iterator itor;
        for(itor = detailColWidth.constBegin(); itor != detailColWidth.constEnd(); itor++ )
        {
            int width=itor.value();
            if(width <= 0)
                width=100;
            else if(width >= this->width())
                width =200;

            ui->detailView->setColumnWidth(itor.key(),width);
        }
    }
}

void Biz::updateStuff(const QString &uid)
{
    stuffModel->setTable(stuffTable);
    stuffModel->setFilter(QString("uid = '%1'").arg(uid));
    stuffModel->select();

    ui->stuffView->hideColumn(0);
    ui->stuffView->hideColumn(1);
    stuffModel->setHeaderData(2,Qt::Horizontal,QStringLiteral("名称"));
    stuffModel->setHeaderData(3,Qt::Horizontal,QStringLiteral("数量"));
    stuffModel->setHeaderData(4,Qt::Horizontal,QStringLiteral("状态"));
    stuffModel->setHeaderData(5,Qt::Horizontal,QStringLiteral("备注"));

    if(loadStuffColWidthFlag)
    {
        QMap<int,int>::const_iterator itor;
        for(itor = stuffColWidth.constBegin(); itor != stuffColWidth.constEnd(); itor++ )
        {
            int width=itor.value();
            if(width <= 0)
                width=100;
            else if(width >= this->width())
                width =200;

            ui->stuffView->setColumnWidth(itor.key(),width);
        }
    }
}

void Biz::en_finish()
{
    QModelIndex index=ui->indexView->currentIndex();
    if(index.isValid())
    {
        QModelIndex mIndex=index.sibling(index.row(),8);
        model->setData(mIndex,ST_FINISH);
    }
}

void Biz::en_finish_direct()
{
    QModelIndex index=ui->indexView->currentIndex();
    if(index.isValid())
    {
        QSqlRecord record=model->record(index.row());
        int id=record.value("id").toInt();
        finishItemDirect(table,id);

        int plan_id = getValue(table,"plan_id",id).toInt();
        if(getStatus(PLAN_EPIBOLY_DETAIL,plan_id) == ST_FINISH)
            return;
        changeStatus(PLAN_EPIBOLY_DETAIL,ST_FINISH,plan_id);
    }
}

void Biz::on_indexView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QSqlRecord record=model->record(index.row());
        QString uid=record.value("uid").toString();
        updateDetail(uid);
        updateStuff(uid);
    }
}

void Biz::on_indexView_doubleClicked(const QModelIndex &index)
{
    if(!isEdit && part != "sd")
        if(index.isValid())
        {
            QSqlRecord record=model->record(index.row());
            QString uid=record.value("uid").toString();
            int index_id=getId(table,uid);
            if(getStatus(table,index_id) == ST_FINISH)
                return;

            DetailAdd detailAdd(this,uid);
            if(detailAdd.exec() == QDialog::Accepted)
            {
                if(getStatus(table,index_id) == ST_RUNNING)
                    return;
                changeStatus(table,ST_RUNNING,index_id);
                updateView();
                updateDetail(uid);
            }
        }
}

void Biz::en_loss()
{
    QModelIndex index=ui->stuffView->currentIndex();
    if(index.isValid())
    {
        QSqlRecord record=stuffModel->record(index.row());
        int stuff_id=record.value("id").toInt();

        QString status = getStatus(stuffTable,stuff_id);
        if(status == ST_LOSS || status == ST_FINISH)
            return;

        QString uid=record.value("uid").toString();
        QString name=record.value("name").toString();
        QString number=record.value("number").toString();
        QString receiver=QStringLiteral("外包报损");

        QSqlQuery query;
        query.prepare("insert into td_loss (date,name,number,receiver,remark,status) values (?,?,?,?,?,?)");
        query.addBindValue(Env::today);
        query.addBindValue(name);
        query.addBindValue(number);
        query.addBindValue(receiver);
        query.addBindValue(getContractorInfo(uid));
        query.addBindValue(ST_WAIT);
        query.exec();

        changeStatus(stuffTable,ST_LOSS,stuff_id);
        updateStuff(uid);

        sendMsg(T_LOSS,LOSS_NOTICE);
    }
}

void Biz::en_stock()
{
    QModelIndex index=ui->detailView->currentIndex();
    if(index.isValid())
    {
        QSqlRecord record=detailModel->record(index.row());
        int id=record.value("id").toInt();
        if(getStatus(detailTable,id) == ST_FINISH)
            return;

        QString uid=record.value("uid").toString();
        QString name=record.value("name").toString();
        QString number=record.value("number").toString();
        QString provider=QStringLiteral("外包入库");

        int index_id=getId(table,uid);
        QString remark=getValue(table,"remark",index_id);

        QSqlQuery query;
        query.prepare("insert into td_stock (date,name,number,provider,remark,status) values (?,?,?,?,?,?)");
        query.addBindValue(Env::today);
        query.addBindValue(name);
        query.addBindValue(number);
        query.addBindValue(provider);
        query.addBindValue(remark);
        query.addBindValue(ST_WAIT);
        query.exec();

        changeStatus(detailTable,ST_FINISH,id);
        updateDetail(uid);
        sendMsg(T_STOCK ,STOCK_NOTICE);
    }
}

QString Biz::getContractorInfo(const QString &uid)
{
    QString info;
    QSqlQuery query;
    query.exec(QString("select date,contractor from %1 where uid='%2'")
               .arg(table)
               .arg(uid));
    if(query.next())
    {
        QString date=query.value(0).toString();
        QString contractor=query.value(1).toString();
        info=date + " " + contractor + QStringLiteral("材料报损");
    }
    else
        info="DB ERROR!";
    return info;
}

void Biz::on_indexView_pressed(const QModelIndex &)
{
    ui->detailView->clearSelection();
    ui->detailView->setCurrentIndex(QModelIndex());
    ui->stuffView->clearSelection();
    ui->stuffView->setCurrentIndex(QModelIndex());
}

void Biz::on_detailView_pressed(const QModelIndex &)
{
    ui->indexView->clearSelection();
    ui->indexView->setCurrentIndex(QModelIndex());
    ui->stuffView->clearSelection();
    ui->stuffView->setCurrentIndex(QModelIndex());
}

void Biz::on_stuffView_pressed(const QModelIndex &)
{
    ui->indexView->clearSelection();
    ui->indexView->setCurrentIndex(QModelIndex());
    ui->detailView->clearSelection();
    ui->detailView->setCurrentIndex(QModelIndex());
}
